package smartcrud.spring.models.crud;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import smartcrud.common.orm.Page;
import smartcrud.common.orm.PropertyFilter;
import smartcrud.common.orm.jdbc.Sql;

@Repository
public class WorldDaoJdbcImpl implements WorldDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Override
	public World createWorld(final World o) {
		final StringBuffer sql = new StringBuffer("insert into CRUD_WORLD(NAME,AGE,SEX,ICON,BIRTH,INTRODUCE,STATUS,CREATE_DATE,UPDATE_DATE)");
		sql.append(" values(?,?,?,?,?,?,?,now(),now())");
        
		KeyHolder keyHolder = new GeneratedKeyHolder();
		jdbcTemplate.update(/* sql, */new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				PreparedStatement ps = con.prepareStatement(sql.toString(),
						Statement.RETURN_GENERATED_KEYS);
				int z = 0;
				ps.setString(++z, o.getName());
				ps.setInt(++z, o.getAge());
				ps.setString(++z, o.getSex());
				ps.setString(++z, o.getIcon());
				ps.setDate(++z, new java.sql.Date(o.getBirth().getTime()));
				ps.setString(++z, o.getIntroduce());
				ps.setInt(++z, o.getStatus());
				return ps;
			}
		}, keyHolder);
		o.setId(keyHolder.getKey().intValue());
		return o;
	}

	@Override
	public void deleteWorld(Long id) {
		jdbcTemplate.update("delete from CRUD_WORLD where ID=?", id);
	}

	@Override
	public void updateWorld(World o) {
	    final StringBuffer sql = new StringBuffer("update CRUD_WORLD set NAME=?,AGE=?,SEX=?,ICON=?,BIRTH=?,INTRODUCE=?,STATUS=?,UPDATE_DATE=now()");
	    sql.append(" where ID=?");       
		jdbcTemplate.update(sql.toString(), 
				o.getName(), 
				o.getAge(), 
				o.getSex(), 
				o.getIcon(), 
				o.getBirth(), 
				o.getIntroduce(), 
				o.getStatus(), 
				o.getId() 
				);
	}

	@Override
	public World findWorldById(Long id) {
		final String sql = "select ID,NAME,AGE,SEX,ICON,BIRTH,INTRODUCE,STATUS,CREATE_DATE,UPDATE_DATE from CRUD_WORLD where ID=?";
		return jdbcTemplate.queryForObject(sql, new RowMapper<World>() {
			@Override
			public World mapRow(ResultSet rs, int rowNum) throws SQLException {
				World o = new World();
				o.setId(rs.getInt("ID"));
				o.setName(rs.getString("NAME"));
				o.setAge(rs.getInt("AGE"));
				o.setSex(rs.getString("SEX"));
				o.setIcon(rs.getString("ICON"));
				o.setBirth(rs.getDate("BIRTH"));
				o.setIntroduce(rs.getString("INTRODUCE"));
				o.setStatus(rs.getInt("STATUS"));
				o.setCreateDate(rs.getDate("CREATE_DATE"));
				o.setUpdateDate(rs.getDate("UPDATE_DATE"));
				return o;
			}
		}, id);
	}

	@Override
	public List<World> findAllWorlds() {
        final String sql = "select ID,NAME,AGE,SEX,ICON,BIRTH,INTRODUCE,STATUS,CREATE_DATE,UPDATE_DATE from CRUD_WORLD";
		return jdbcTemplate.query(sql, new RowMapper<World>() {
			@Override
			public World mapRow(ResultSet rs, int rowNum) throws SQLException {
				World o = new World();
				o.setId(rs.getInt("ID"));
				o.setName(rs.getString("NAME"));
				o.setAge(rs.getInt("AGE"));
				o.setSex(rs.getString("SEX"));
				o.setIcon(rs.getString("ICON"));
				o.setBirth(rs.getDate("BIRTH"));
				o.setIntroduce(rs.getString("INTRODUCE"));
				o.setStatus(rs.getInt("STATUS"));
				o.setCreateDate(rs.getDate("CREATE_DATE"));
				o.setUpdateDate(rs.getDate("UPDATE_DATE"));
				return o;
			}
		});
	}
	
    @Override
    public int count() {
        return jdbcTemplate.queryForInt("select count(1) from CRUD_WORLD");
    }
    
	@Override
	public int count(Page<World> page,final List<PropertyFilter> filters) {
		Sql sql = new Sql("select count(1) from CRUD_WORLD where 1=1 ", page,filters);
		sql.build4count();
		return jdbcTemplate.queryForInt(sql.getSqlBody(), sql.getSqlParams());
	}

	@Override
	public Page<World> findByPage(Page<World> page, final List<PropertyFilter> filters) {
		if (page.isAutoCount()) {
			int totalCount = count(page, filters);
			page.setTotalCount(totalCount);
		}
		
		Sql sql = new Sql("select * from CRUD_WORLD where 1=1 ", page, filters);
		sql.build();

		List<World> content = jdbcTemplate.query(sql.getSqlBody(),
				new RowMapper<World>() {
					@Override
					public World mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						World o = new World();
						o.setId(rs.getInt("ID"));
						o.setName(rs.getString("NAME"));
						o.setAge(rs.getInt("AGE"));
						o.setSex(rs.getString("SEX"));
						o.setIcon(rs.getString("ICON"));
						o.setBirth(rs.getDate("BIRTH"));
						o.setIntroduce(rs.getString("INTRODUCE"));
						o.setStatus(rs.getInt("STATUS"));
						o.setCreateDate(rs.getDate("CREATE_DATE"));
						o.setUpdateDate(rs.getDate("UPDATE_DATE"));
						return o;
					}
				}, sql.getSqlParams());

		page.setContent(content);
		return page;
	}

}
